<template>
  <div style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAdd">新增</el-button>
        <el-button @click="start">启用</el-button>
        <el-button @click="block">停用</el-button>

      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
      :loading="loading"
      align="center"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      :export-config='{type:"csv"}'
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="150" sortable show-header-overflow show-overflow
                          :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.status" placeholder="请选择状态" clearable>
            <el-option value="0" label="启用"/>
            <el-option value="1" label="停用"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="serialNumber" title="仓库编码" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.serialNumber" placeholder="请输入仓库编码" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="name" title="仓库名称" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.name" placeholder="请输入仓库名称" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="type" title="仓库类型" min-width="200" sortable show-header-overflow show-overflow
                          :formatter="formatterType"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.type" placeholder="请选择仓库类型" clearable>
            <el-option value="1" label="生产仓"/>
            <el-option value="2" label="原料仓"/>
            <el-option value="3" label="成品仓"/>
            <el-option value="4" label="普通仓"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="locationManagement" title="启用库位管理" min-width="200" sortable show-header-overflow show-overflow :formatter="formatterlocationManagement"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.locationManagement" placeholder="请选择是否启用" clearable>
            <el-option value="0" label="不启用"/>
            <el-option value="1" label="启用"/>
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="contacts" title="联系人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.contacts " placeholder="请输入联系人" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="landlineNumber" title="联系人电话" min-width="200" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.landlineNumber" placeholder="请输入联系人电话" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="phoneNumber" title="手机号" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.phoneNumber" placeholder="请输入手机号" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="fax" title="传真" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.fax" placeholder="请输入传真" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="email" title="邮箱" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.email " placeholder="请输入邮箱" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="address" title="地址" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.address " placeholder="请输入地址" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="longitude" title="坐标（x）" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.longitude" placeholder="请输入坐标（x）" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="latitude" title="坐标（y)" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.latitude" placeholder="请输入坐标（y)" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable/>
        </template>
      </vxe-table-column>
      <!--<vxe-table-column>
        <vxe-table-column field="gmtCreated" title="创建时间" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.gmtCreated" placeholder="请输入创建时间" clearable/>
        </template>
      </vxe-table-column>-->
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          show-header-overflow
          show-overflow
          title="创建时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="modifiedName" title="修改人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.modifiedName" placeholder="请输入修改人" clearable/>
        </template>
      </vxe-table-column>
      <!--<vxe-table-column>
        <vxe-table-column field="gmtModified" title="修改时间" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.gmtModified" placeholder="请输入修改时间" clearable/>
        </template>
      </vxe-table-column>-->
      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          show-header-overflow
          show-overflow
          title="修改时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>


      <vxe-table-column title="操作" fixed="right" min-width="180">
        <template slot-scope="scope">
          <el-tooltip  effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document"/>
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="编辑" placement="top">
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit"/>
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="funcDelete(scope.row.code)">
              <i class="el-icon-delete"/>
            </vxe-button>
          </el-tooltip>
          <!-- <el-tooltip  effect="dark" content="绑定入驻商" placement="top">
            <vxe-button type="text" @click="binding(scope.row.code)">
              <i class="el-icon-paperclip"/>
            </vxe-button>
          </el-tooltip> -->
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="modelAddFlag" title="新增" width="1100" height="650" destroy-on-close resize>
      <compAdd ref="addRef" @fatherAddMethod="fatherAdd" />
    </vxe-modal>
    <vxe-modal v-model="modelEditFlag" title="编辑" width="1100" height="650" destroy-on-close resize>
      <compEdit ref="editRef" @fatherEditMethod="fatherEdit" @fatherCancelMethod="fatherCancel" :operationCode="operationCode" />
    </vxe-modal>
    <vxe-modal v-model="modelDetailFlag" title="详情" width="1100" height="650" destroy-on-close resize>
      <compDetail ref="detailRef"  :operationCode="operationCode" />
    </vxe-modal>
    <vxe-modal v-model="modelbindingFlag" title="绑定入驻商" width="1100" height="730" resize>
      <compBinding ref="bindingRef"/>
    </vxe-modal>

  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'

  Vue.use(VXETable, VXEUtils, XEUtils, {mounts: ['cookie']})
  import compAdd from './components/WarehouseAdd.vue'
  import compEdit from './components/WarehouseEdit.vue'
  import compBinding from './components/binding.vue'
  import compDetail from './components/WarehouseDetail.vue'
  import {warehouseList, active, unActive, warehouseDelete} from '@/api/basicInfo'

  export default {
    name: 'Parent',
    components: {
      compAdd,
      compEdit,
      compDetail,
      compBinding
    },
    data() {
      return {
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        },

        message: '',
        loading: false,
        tableData: [],
        modelAddFlag: false,
        modelbindingFlag: false,
        modelEditFlag: false,
        modelDetailFlag: false,
          gmtCreatedRange:"",
          gmtModifiedRange:"",
        copy: false,
        listQuery: {
          address: '',        //地址
          city: '',           //市
          code: '',           //数据标识
          contacts: '',       //联系人
          locationManagement:'',
          country: '',        //国家
          county: '',         //县/区
          email: '',          //邮箱
          fax: '',            //传真
          groupCode: '',      //所属组织
          landlineNumber: '', //联系人号码
          latitude: '',       //维度
          longitude: '',      //经度
          name: '',           //仓库名称
          phoneNumber: '',    //手机号码
          province: '',       //省
          remarks: '',        //备注
          serialNumber: '',   //仓库代码
          createdBy: '',      //创建人
          createdName: '',      //创建人
          modifiedBy: '',     //修改人
          modifiedName: '',     //修改人
          gmtCreated: '',     //创建时间
          gmtModified: '',    //修改时间
          status: '',         //状态
          total: 0,          //总数
          type: '',           //仓库类型
          pageNum: 1,
          pageSize: 10,
          sortField: '',
          sortType: '',
        },
        // 所属仓库
        warehouseList: [],
        // 所属库区
        warehouseSpaceList: [],
        // 新所属库区
        warehouseSpaceListNew: [],
        operationCode:[], // 编辑、查看 接口所需id
        warehouseDetail:[]
      }
    },
    created() {
      this.findList()
    },
    methods: {
      //启用
      start() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        arr = arr.join(",");
        if (arr.length != 0) {
          this.$confirm('确认启用吗？').then(_ => {
            this.loading = true
            active(arr).then(response => {
              this.$message({message: response.msg, type: 'success'})
              this.findList()
              this.loading = false
            })
          })
        } else {
          this.$message('没有能启用的数据！')
        }

      },
        changeDate(value, prefix) {
            if (value) {
                this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
                this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
            } else {
                this.listQuery[`${prefix}Start`] = "";
                this.listQuery[`${prefix}End`] = "";
            }
        },
      //停用
      block() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        arr = arr.join(",");
        if (arr.length != 0) {
          this.$confirm('确认停用吗？').then(_ => {
            this.loading = true
            unActive(arr).then(response => {
              this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
              this.findList()
              this.loading = false
            })
          }).catch(_ => {
          })
        } else {
          this.$message('没有能停用的数据！')
        }
      },
      formatterlocationManagement({cellValue}) {
        if (cellValue == '0') {
          return '不启用'
        } else if (cellValue == '1') {
          return '启用'
        }
      },
      // 翻译状态
      formatterStatus({cellValue}) {
        if (cellValue === '0') {
          return '启用'
        } else if (cellValue === '1') {
          return '停用'
        }
      },
        formatterType({cellValue}){
            if (cellValue === '1') {
                return '生产仓'
            } else if (cellValue === '2') {
                return '原料仓'
            }else if (cellValue === '3') {
                return '成品仓'
            } else if (cellValue === '4') {
                return '普通仓'
            }
        },

      //绑定入驻商
      binding(code) {
        this.$refs.bindingRef.getInfo(code)
        this.$refs.bindingRef.findWarehouseShipmentList(code)
        this.modelbindingFlag = true
      },
      //获取列表
      findList() {
        this.loading = true
        return warehouseList(this.listQuery).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
          this.loading = false
        })
      },
      // 排序
      sortList({column, property, order}) {
        if (order) {
          this.listQuery.sortField = property
          this.listQuery.sortType = order
        } else {
          this.listQuery.sortField = ''
        }
        this.findList()
      },
      // 添加方法
      funcAdd() {
        this.modelAddFlag = true
      },
      // 修改方法
      funcEdit(code) {
        this.operationCode = code
        this.modelEditFlag = true
      },
      // 详情方法
      funcDetail(code) {
       this.operationCode = code
        this.modelDetailFlag = true
      },
      // 删除方法
      funcDelete(row) {
        this.$confirm('确认删除吗？').then(_ => {
          warehouseDelete(row).then(response => {
            this.$message({ dangerouslyUseHTMLString: true,message: response.msg, type: 'success'})
            this.findList()
          })
        }).catch(_ => {
        })
      },
      // 增加组件的父方法
      fatherAdd() {
        this.modelAddFlag = false
        this.findList()
      },
      // 编辑组件的父方法
      fatherEdit() {
        this.modelEditFlag = false
        this.findList()
      },
      // 公共取消
      fatherCancel(modelFlag) {
        switch (modelFlag) {
          case 'add':
            this.modelAddFlag = false
            break
          case 'edit':
            this.modelEditFlag = false
            break
          case 'detail':
            this.modelDetailFlag = false
            break
          default:
        }
      },
      // 分页handle
      handlePageChange({currentPage, pageSize}) {
        this.listQuery.pageNum = currentPage
        this.listQuery.pageSize = pageSize
        this.findList()
      },
      // 设置底部合计
      footerMethod({columns, data}) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (['pageviews', 'forecast'].includes(column.property)) {
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]
      }
    }
  }
</script>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }

  .vxe-toolbar {
    padding: 0 0 10px 0
  }
</style>
